<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智习伴 - 学生端</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.19/tailwind.min.css">
    <link rel="stylesheet" href="static/css/style.css">
    <style>
        .camera-preview {
            max-width: 100%;
            max-height: 300px;
            display: none;
        }
        .file-preview {
            max-width: 100%;
            max-height: 300px;
            display: none;
        }
        .spinner {
            display: inline-block;
            width: 1rem;
            height: 1rem;
            border: 2px solid rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            border-top-color: white;
            animation: spin 1s ease-in-out infinite;
        }
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        .resource-link {
            transition: all 0.3s ease;
        }
        .resource-link:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
    </style>
</head>
<body class="bg-gray-100 bg-pattern">
    <div class="min-h-screen">
        <!-- 头部导航 -->
        <nav class="bg-white shadow">
            <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                <div class="flex justify-between h-16">
                    <div class="flex">
                        <div class="flex-shrink-0 flex items-center">
                            <h1 class="text-xl font-bold text-gray-800">智习伴</h1>
                        </div>
                    </div>
                    <div class="flex items-center">
                        <button id="logoutBtn" class="ml-4 px-4 py-2 text-sm font-medium text-gray-700 hover:text-gray-900">
                            退出登录
                        </button>
                    </div>
                </div>
            </div>
        </nav>

        <!-- 主要内容 -->
        <main class="max-w-7xl mx-auto py-6 sm:px-6 lg:px-8">
            <div class="px-4 py-6 sm:px-0">
                <div class="bg-white shadow overflow-hidden sm:rounded-lg">
                    <div class="px-4 py-5 sm:px-6">
                        <h3 class="text-lg leading-6 font-medium text-gray-900">学习助手</h3>
                        <p class="mt-1 max-w-2xl text-sm text-gray-500">向AI提问任何学习相关的问题</p>
                    </div>
                    <div class="border-t border-gray-200">
                        <div class="p-6">
                            <form id="questionForm" class="mb-6">
                                <div class="mb-4">
                                    <label for="subject" class="block text-sm font-medium text-gray-700">科目</label>
                                    <select id="subject" class="mt-1 block w-full py-2 px-3 border border-gray-300 bg-white rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 form-input">
                                        <option value="chinese">语文</option>
                                        <option value="math">数学</option>
                                        <option value="english">英语</option>
                                        <option value="physics">物理</option>
                                        <option value="chemistry">化学</option>
                                        <option value="biology">生物</option>
                                        <option value="geography">地理</option>
                                        <option value="politics">政治</option>
                                        <option value="history">历史</option>
                                    </select>
                                </div>
                                
                                <div class="mb-4">
                                    <label class="block text-sm font-medium text-gray-700 mb-2">问题输入方式</label>
                                    <div class="flex space-x-4">
                                        <button type="button" id="textMode" class="px-4 py-2 bg-blue-600 text-white rounded-md btn-primary">文字输入</button>
                                        <button type="button" id="cameraMode" class="px-4 py-2 bg-gray-200 text-gray-700 rounded-md btn-secondary">拍照提问</button>
                                        <button type="button" id="fileMode" class="px-4 py-2 bg-gray-200 text-gray-700 rounded-md btn-secondary">上传文件</button>
                                    </div>
                                </div>
                                
                                <!-- 文字输入模式 -->
                                <div id="textInputSection" class="mb-4">
                                    <label for="question" class="block text-sm font-medium text-gray-700">问题</label>
                                    <textarea id="question" rows="4" class="mt-1 block w-full border border-gray-300 rounded-md shadow-sm focus:ring-blue-500 focus:border-blue-500 form-input" placeholder="请输入你的问题..."></textarea>
                                </div>
                                
                                <!-- 拍照模式 -->
                                <div id="cameraSection" class="mb-4 hidden">
                                    <label class="block text-sm font-medium text-gray-700 mb-2">拍照提问</label>
                                    <div class="flex flex-col items-center">
                                        <video id="cameraPreview" class="camera-preview mb-2"></video>
                                        <img id="capturedImage" class="camera-preview mb-2" alt="Captured image">
                                        <canvas id="canvas" class="hidden"></canvas>
                                        <div class="flex space-x-2 mt-2">
                                            <button type="button" id="startCamera" class="px-4 py-2 bg-blue-600 text-white rounded-md btn-primary">开启摄像头</button>
                                            <button type="button" id="captureBtn" class="px-4 py-2 bg-green-600 text-white rounded-md btn-primary hidden">拍照</button>
                                            <button type="button" id="retakeBtn" class="px-4 py-2 bg-yellow-600 text-white rounded-md btn-primary hidden">重新拍照</button>
                                        </div>
                                        <input type="hidden" id="capturedImageData">
                                    </div>
                                </div>
                                
                                <!-- 文件上传模式 -->
                                <div id="fileSection" class="mb-4 hidden">
                                    <label class="block text-sm font-medium text-gray-700 mb-2">上传文件或图片</label>
                                    <div class="flex items-center space-x-2">
                                        <input type="file" id="fileInput" class="block w-full text-sm text-gray-500
                                            file:mr-4 file:py-2 file:px-4
                                            file:rounded-md file:border-0
                                            file:text-sm file:font-semibold
                                            file:bg-blue-50 file:text-blue-700
                                            hover:file:bg-blue-100" accept="image/*,.pdf,.doc,.docx,.txt">
                                        <img id="filePreview" class="file-preview" alt="File preview">
                                    </div>
                                </div>
                                
                                <button type="submit" class="inline-flex items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 btn-primary">
                                    提交问题
                                </button>
                            </form>

                            <div id="answerContainer" class="hidden mb-6">
                                <h4 class="text-md font-medium text-gray-900 mb-2">AI回答：</h4>
                                <div id="answerContent" class="bg-gray-50 p-4 rounded-md"></div>
                            </div>
                            
                            <!-- 相关资源推荐 -->
                            <div id="resourcesContainer" class="hidden mb-6">
                                <h4 class="text-md font-medium text-gray-900 mb-2">相关学习资源：</h4>
                                <div id="resourcesList" class="grid grid-cols-1 md:grid-cols-2 gap-4"></div>
                            </div>
                            
                            <!-- 相关例题 -->
                            <div id="examplesContainer" class="hidden mb-6">
                                <h4 class="text-md font-medium text-gray-900 mb-2">相关例题：</h4>
                                <div id="examplesList" class="space-y-4"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>

    <script src="static/js/main.js"></script>
    <script>
        // 页面加载完成后执行
        document.addEventListener('DOMContentLoaded', function() {
            // 检查用户是否已登录
            checkUserAuthentication();
            
            // 初始化页面功能
            initializeStudentPage();
        });
        
        // 检查用户身份验证
        function checkUserAuthentication() {
            const user = localStorage.getItem('user');
            const token = localStorage.getItem('token');
            
            if (!user || !token) {
                utils.showMessage('请先登录', 'error');
                setTimeout(() => {
                    window.location.href = 'login.html';
                }, 1500);
                return false;
            }
            
            // 可以在这里添加更多验证逻辑，比如检查token是否过期等
            return true;
        }
        
        // 初始化学生页面
        function initializeStudentPage() {
            // 绑定事件监听器
            document.getElementById('submitQuestionBtn').addEventListener('click', handleSubmitQuestion);
            document.getElementById('voiceInputBtn').addEventListener('click', handleVoiceInput);
            document.getElementById('logoutBtn').addEventListener('click', handleLogout);
            
            // 为评分按钮添加事件监听器
            const ratingButtons = document.querySelectorAll('.rating-btn');
            ratingButtons.forEach(button => {
                button.addEventListener('click', function() {
                    const rating = this.getAttribute('data-rating');
                    handleRating(rating);
                });
            });
        }
        
        // 处理退出登录
        function handleLogout() {
            if (utils.confirmAction('确定要退出登录吗？')) {
                // 清除本地存储的用户信息
                localStorage.removeItem('token');
                localStorage.removeItem('user');
                
                utils.showMessage('已退出登录');
                setTimeout(() => {
                    window.location.href = 'login.html';
                }, 1000);
            }
        }
        
        // 模式切换
        const textMode = document.getElementById('textMode');
        const cameraMode = document.getElementById('cameraMode');
        const fileMode = document.getElementById('fileMode');
        const textInputSection = document.getElementById('textInputSection');
        const cameraSection = document.getElementById('cameraSection');
        const fileSection = document.getElementById('fileSection');
        
        textMode.addEventListener('click', () => {
            textMode.classList.remove('bg-gray-200', 'text-gray-700');
            textMode.classList.add('bg-blue-600', 'text-white');
            cameraMode.classList.remove('bg-blue-600', 'text-white');
            cameraMode.classList.add('bg-gray-200', 'text-gray-700');
            fileMode.classList.remove('bg-blue-600', 'text-white');
            fileMode.classList.add('bg-gray-200', 'text-gray-700');
            
            textInputSection.classList.remove('hidden');
            cameraSection.classList.add('hidden');
            fileSection.classList.add('hidden');
            
            stopCamera();
        });
        
        cameraMode.addEventListener('click', () => {
            textMode.classList.remove('bg-blue-600', 'text-white');
            textMode.classList.add('bg-gray-200', 'text-gray-700');
            cameraMode.classList.remove('bg-gray-200', 'text-gray-700');
            cameraMode.classList.add('bg-blue-600', 'text-white');
            fileMode.classList.remove('bg-blue-600', 'text-white');
            fileMode.classList.add('bg-gray-200', 'text-gray-700');
            
            textInputSection.classList.add('hidden');
            cameraSection.classList.remove('hidden');
            fileSection.classList.add('hidden');
        });
        
        fileMode.addEventListener('click', () => {
            textMode.classList.remove('bg-blue-600', 'text-white');
            textMode.classList.add('bg-gray-200', 'text-gray-700');
            cameraMode.classList.remove('bg-blue-600', 'text-white');
            cameraMode.classList.add('bg-gray-200', 'text-gray-700');
            fileMode.classList.remove('bg-gray-200', 'text-gray-700');
            fileMode.classList.add('bg-blue-600', 'text-white');
            
            textInputSection.classList.add('hidden');
            cameraSection.classList.add('hidden');
            fileSection.classList.remove('hidden');
        });
        
        // 摄像头功能
        let videoStream = null;
        const cameraPreview = document.getElementById('cameraPreview');
        const capturedImage = document.getElementById('capturedImage');
        const canvas = document.getElementById('canvas');
        const startCameraBtn = document.getElementById('startCamera');
        const captureBtn = document.getElementById('captureBtn');
        const retakeBtn = document.getElementById('retakeBtn');
        const capturedImageData = document.getElementById('capturedImageData');
        
        startCameraBtn.addEventListener('click', startCamera);
        captureBtn.addEventListener('click', captureImage);
        retakeBtn.addEventListener('click', retakeImage);
        
        function startCamera() {
            if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
                navigator.mediaDevices.getUserMedia({ video: true })
                    .then(function(stream) {
                        videoStream = stream;
                        cameraPreview.srcObject = stream;
                        cameraPreview.style.display = 'block';
                        capturedImage.style.display = 'none';
                        captureBtn.classList.remove('hidden');
                        startCameraBtn.textContent = '摄像头已开启';
                        startCameraBtn.disabled = true;
                    })
                    .catch(function(error) {
                        console.error("无法访问摄像头:", error);
                        utils.showMessage('无法访问摄像头，请检查权限设置', 'error');
                    });
            } else {
                utils.showMessage('您的浏览器不支持摄像头功能', 'error');
            }
        }
        
        function captureImage() {
            const context = canvas.getContext('2d');
            canvas.width = cameraPreview.videoWidth;
            canvas.height = cameraPreview.videoHeight;
            context.drawImage(cameraPreview, 0, 0, canvas.width, canvas.height);
            
            const dataUrl = canvas.toDataURL('image/png');
            capturedImage.src = dataUrl;
            capturedImage.style.display = 'block';
            cameraPreview.style.display = 'none';
            capturedImageData.value = dataUrl;
            
            captureBtn.classList.add('hidden');
            retakeBtn.classList.remove('hidden');
        }
        
        function retakeImage() {
            cameraPreview.style.display = 'block';
            capturedImage.style.display = 'none';
            captureBtn.classList.remove('hidden');
            retakeBtn.classList.add('hidden');
            capturedImageData.value = '';
        }
        
        function stopCamera() {
            if (videoStream) {
                const tracks = videoStream.getTracks();
                tracks.forEach(track => track.stop());
                videoStream = null;
            }
            cameraPreview.srcObject = null;
            startCameraBtn.textContent = '开启摄像头';
            startCameraBtn.disabled = false;
            captureBtn.classList.add('hidden');
            retakeBtn.classList.add('hidden');
            capturedImageData.value = '';
        }
        
        // 文件上传预览
        utils.setupFilePreview('fileInput', 'filePreview');
        
        // 模拟网络资源数据
        const webResources = {
            chinese: [
                { title: "古诗词鉴赏技巧", url: "https://www.bilibili.com/video/BV1xx411c7mu", source: "B站" },
                { title: "文言文翻译方法", url: "https://www.bilibili.com/video/BV1bt411T7nu", source: "B站" },
                { title: "现代文阅读理解", url: "https://www.bilibili.com/video/BV1XJ411J78z", source: "B站" }
            ],
            math: [
                { title: "高中数学知识点总结", url: "https://www.bilibili.com/video/BV1Eb411f7cV", source: "B站" },
                { title: "三角函数公式推导", url: "https://www.bilibili.com/video/BV1Js41157S6", source: "B站" },
                { title: "导数与微积分入门", url: "https://www.bilibili.com/video/BV17J411g7CF", source: "B站" }
            ],
            english: [
                { title: "高考英语语法精讲", url: "https://www.bilibili.com/video/BV1Yb411c7ST", source: "B站" },
                { title: "英语单词记忆法", url: "https://www.bilibili.com/video/BV1Lt411U7QP", source: "B站" },
                { title: "英语写作技巧", url: "https://www.bilibili.com/video/BV1KW411875r", source: "B站" }
            ],
            physics: [
                { title: "力学知识点详解", url: "https://www.bilibili.com/video/BV18t411q7zz", source: "B站" },
                { title: "电磁学入门", url: "https://www.bilibili.com/video/BV12t411K7Pj", source: "B站" },
                { title: "光学原理讲解", url: "https://www.bilibili.com/video/BV1Lt411U77J", source: "B站" }
            ],
            chemistry: [
                { title: "化学方程式配平", url: "https://www.bilibili.com/video/BV17t411q7zz", source: "B站" },
                { title: "有机化学基础", url: "https://www.bilibili.com/video/BV1bt411q7pJ", source: "B站" },
                { title: "化学实验操作", url: "https://www.bilibili.com/video/BV1Lt411U77J", source: "B站" }
            ],
            biology: [
                { title: "细胞生物学", url: "https://www.bilibili.com/video/BV1Xt411q7zz", source: "B站" },
                { title: "遗传学基础", url: "https://www.bilibili.com/video/BV1bt411q7pJ", source: "B站" },
                { title: "生态学入门", url: "https://www.bilibili.com/video/BV1Lt411U77J", source: "B站" }
            ],
            geography: [
                { title: "自然地理学", url: "https://www.bilibili.com/video/BV1Zt411q7zz", source: "B站" },
                { title: "人文地理学", url: "https://www.bilibili.com/video/BV1ct411q7pJ", source: "B站" },
                { title: "地图学基础", url: "https://www.bilibili.com/video/BV1Mt411U77J", source: "B站" }
            ],
            politics: [
                { title: "马克思主义原理", url: "https://www.bilibili.com/video/BV1Tt411q7zz", source: "B站" },
                { title: "中国特色社会主义", url: "https://www.bilibili.com/video/BV1dt411q7pJ", source: "B站" },
                { title: "政治经济学基础", url: "https://www.bilibili.com/video/BV1Nt411U77J", source: "B站" }
            ]
        };
        
        // 模拟例题数据
        const exampleProblems = {
            math: [
                {
                    problem: "已知函数 f(x) = x² + 2x + 1，求 f(x) 的最小值。",
                    solution: "解：f(x) = x² + 2x + 1 = (x + 1)²\n因为平方数非负，所以当 x = -1 时，f(x) 取得最小值 0。"
                },
                {
                    problem: "在三角形ABC中，已知角A=60°，边a=3，边b=2√3，求边c的长度。",
                    solution: "解：由余弦定理得：a² = b² + c² - 2bc·cosA\n代入数值：9 = 12 + c² - 2×2√3×c×cos60°\n化简得：c² - 2√3c + 3 = 0\n解得：c = √3"
                }
            ],
            english: [
                {
                    problem: "选择正确的单词填空：The ______ of the story is very important. (moral/morale)",
                    solution: "答案：moral\n解析：moral 指道德、寓意，morale 指士气。在这个句子中，表示故事的寓意，所以用 moral。"
                }
            ],
            physics: [
                {
                    problem: "一个物体从静止开始做匀加速直线运动，加速度为2m/s²，求3秒后的速度和位移。",
                    solution: "解：已知初速度v₀=0，加速度a=2m/s²，时间t=3s\n由v = v₀ + at得：v = 0 + 2×3 = 6m/s\n由s = v₀t + ½at²得：s = 0 + ½×2×3² = 9m\n所以3秒后速度为6m/s，位移为9m。"
                }
            ],
            chemistry: [
                {
                    problem: "配平化学方程式：Fe + H₂O → Fe₃O₄ + H₂",
                    solution: "解：观察反应物和生成物中各元素的原子数\n左边：Fe:1, H:2, O:1\n右边：Fe:3, H:2, O:4\n配平后：3Fe + 4H₂O → Fe₃O₄ + 4H₂"
                }
            ]
        };
        
        // 处理提交问题
        document.getElementById('questionForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const subjectCode = document.getElementById('subject').value;
            const questionText = document.getElementById('question').value;
            const capturedImageData = document.getElementById('capturedImageData').value;
            const fileInput = document.getElementById('fileInput');
            
            // 检查输入
            if (!subjectCode) {
                utils.showMessage('请选择科目', 'error');
                return;
            }
            
            // 检查是否有问题内容（文字或图片）
            if (!questionText && !capturedImageData && fileInput.files.length === 0) {
                utils.showMessage('请输入问题或上传图片', 'error');
                return;
            }
            
            // 获取提交按钮以显示加载状态
            const submitButton = this.querySelector('button[type="submit"]');
            const originalText = submitButton.textContent;
            utils.showLoading(submitButton);
            
            // 准备请求数据
            const requestData = {
                subject_code: subjectCode
            };
            
            // 添加文字问题（如果有）
            if (questionText) {
                requestData.question = questionText;
            }
            
            // 添加拍照图片数据（如果有）
            if (capturedImageData) {
                requestData.image_data = capturedImageData;
            }
            
            // 添加文件上传图片数据（如果有）
            if (fileInput.files.length > 0) {
                const file = fileInput.files[0];
                const reader = new FileReader();
                reader.onload = function(e) {
                    requestData.image_data = e.target.result;
                    sendQuestionRequest(requestData, submitButton, originalText);
                };
                reader.readAsDataURL(file);
                return;
            }
            
            // 发送请求
            sendQuestionRequest(requestData, submitButton, originalText);
        });
        
        // 发送问题请求到后端
        function sendQuestionRequest(requestData, submitButton, originalText) {
            // 获取JWT令牌
            const token = localStorage.getItem('token');
            
            fetch('/api/questions/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify(requestData)
            })
            .then(response => response.json())
            .then(data => {
                utils.hideLoading(submitButton, originalText);
                
                if (data.error) {
                    utils.showMessage(data.error, 'error');
                    return;
                }
                
                // 显示答案
                document.getElementById('answerContent').innerHTML = utils.formatAnswer(data.answer);
                document.getElementById('answerContainer').classList.remove('hidden');
                
                // 显示相关资源和例题
                const subject = requestData.subject_code;
                displayResources(subject);
                displayExamples(subject);
                
                // 清空输入
                document.getElementById('question').value = '';
                document.getElementById('capturedImageData').value = '';
                document.getElementById('fileInput').value = '';
                document.getElementById('filePreview').style.display = 'none';
                document.getElementById('capturedImage').style.display = 'none';
                document.getElementById('cameraPreview').style.display = 'none';
                stopCamera();
                
                utils.showMessage('问题提交成功', 'success');
            })
            .catch(error => {
                utils.hideLoading(submitButton, originalText);
                console.error('Error:', error);
                utils.showMessage('提交问题失败，请稍后重试', 'error');
            });
        }
        
        // 显示相关资源
        function displayResources(subject) {
            const resourcesList = document.getElementById('resourcesList');
            const resourcesContainer = document.getElementById('resourcesContainer');
            
            if (webResources[subject] && webResources[subject].length > 0) {
                let resourcesHTML = '';
                webResources[subject].forEach(resource => {
                    // 根据学科和资源标题生成B站搜索链接
                    let searchQuery = '';
                    switch(subject) {
                        case 'chinese':
                            searchQuery = '语文 ' + resource.title;
                            break;
                        case 'math':
                            searchQuery = '数学 ' + resource.title;
                            break;
                        case 'english':
                            searchQuery = '英语 ' + resource.title;
                            break;
                        case 'physics':
                            searchQuery = '物理 ' + resource.title;
                            break;
                        case 'chemistry':
                            searchQuery = '化学 ' + resource.title;
                            break;
                        case 'biology':
                            searchQuery = '生物 ' + resource.title;
                            break;
                        case 'geography':
                            searchQuery = '地理 ' + resource.title;
                            break;
                        case 'politics':
                            searchQuery = '政治 ' + resource.title;
                            break;
                        default:
                            searchQuery = resource.title;
                    }
                    
                    // 生成B站搜索链接
                    const bilibiliUrl = `https://search.bilibili.com/all?keyword=${encodeURIComponent(searchQuery)}`;
                    
                    resourcesHTML += `
                        <a href="${bilibiliUrl}" target="_blank" class="resource-link block p-4 bg-blue-50 rounded-lg border border-blue-200 hover:bg-blue-100">
                            <div class="font-medium text-blue-800">${resource.title}</div>
                            <div class="text-sm text-blue-600">B站搜索</div>
                        </a>
                    `;
                });
                resourcesList.innerHTML = resourcesHTML;
                resourcesContainer.classList.remove('hidden');
            } else {
                resourcesContainer.classList.add('hidden');
            }
        }
        
        // 显示相关例题
        function displayExamples(subject) {
            const examplesList = document.getElementById('examplesList');
            const examplesContainer = document.getElementById('examplesContainer');
            
            if (exampleProblems[subject] && exampleProblems[subject].length > 0) {
                let examplesHTML = '';
                exampleProblems[subject].forEach(example => {
                    examplesHTML += `
                        <div class="p-4 bg-gray-50 rounded-lg border border-gray-200">
                            <div class="font-medium text-gray-800 mb-2">题目：</div>
                            <div class="mb-3">${example.problem}</div>
                            <div class="font-medium text-gray-800 mb-2">解答：</div>
                            <div class="whitespace-pre-line">${example.solution}</div>
                        </div>
                    `;
                });
                examplesList.innerHTML = examplesHTML;
                examplesContainer.classList.remove('hidden');
            } else {
                examplesContainer.classList.add('hidden');
            }
        }
        
        document.getElementById('logoutBtn').addEventListener('click', function() {
            if (utils.confirmAction('确定要退出登录吗？')) {
                utils.showMessage('已退出登录');
                setTimeout(() => {
                    window.location.href = 'login.html';
                }, 1000);
            }
        });
    </script>
</body>
</html>